﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace Iit.ITBI.MDSManager
{
    class MetadataCache
    {

        public string mdsdbConnectionString
        {
            get;
            set;
        }

        public Collection<MasterToSlaveEntityMapping> MasterToSlaveMappings
        {
            get;
            set;
        }

        public MetadataCache(string mdsdbConnectionString)
        {
            this.mdsdbConnectionString = mdsdbConnectionString;

            MDSSqlWrapper.Ininitalize(this.mdsdbConnectionString);

            this.MasterToSlaveMappings = new Collection<MasterToSlaveEntityMapping>();
            
        }

        public void RefreshLocalCache()
        {

            this.MasterToSlaveMappings.Clear();

            CustomDataTable masterToSlaveMappings;
            CustomDataTable attributeDetails;
            CustomDataTable entitiesSyncState;
            
            masterToSlaveMappings = MDSSqlWrapper.GlobalInstance.GetMasterToSlaveList();
            
            attributeDetails = MDSSqlWrapper.GlobalInstance.GetAttributeDetails();
            
            entitiesSyncState = MDSSqlWrapper.GlobalInstance.EntitiesSyncState();
            
            foreach (DataRow dr in masterToSlaveMappings.Rows)
            {
                MasterToSlaveEntityMapping m2s = new MasterToSlaveEntityMapping(dr, masterToSlaveMappings.QueryVersion);

                m2s.PopulateAttributesDetails(attributeDetails);

                if (m2s.HasOnlySystemAttributes == false)
                {
                    m2s.SetEntitySyncState(entitiesSyncState);
                }

                MasterToSlaveMappings.Add(m2s);
                   
            }           
         
        }


        public override string ToString()
        {
            StringBuilder str = new StringBuilder();

            str.AppendLine("************************************************************************");
            str.AppendLine("Entity Mappings");
            str.AppendLine("************************************************************************");
            str.AppendLine();
            
            foreach (MasterToSlaveEntityMapping m in MasterToSlaveMappings)
            {
                str.AppendLine(m.ToString());
            }
            str.AppendLine("************************************************************************");
            str.AppendLine();

            return str.ToString();
        }

    }



}

